package cn.zhiran.user.service.impl;

import cn.zhiran.basic.exception.BusinessException;
import cn.zhiran.basic.util.SmsUtil;
import cn.zhiran.basic.util.StrUtils;
import cn.zhiran.user.UserConstants;
import cn.zhiran.user.domain.User;
import cn.zhiran.user.mapper.UserMapper;
import cn.zhiran.user.service.IVerifycodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 用户注册验证码操作
 */
public class VerifycodeServiceImpl implements IVerifycodeService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendSmsCode(String phone) throws Exception {
        //1.非空校验
        if(StringUtils.isEmpty(phone)){   //手机号为空
            throw new BusinessException("手机号不能为空");
        }
        //2.手机号是否注册  查user表
        User user=userMapper.findByPhone(phone);
        if(user!=null){
            throw new BusinessException("手机号已被注册，请直接登录");
        }
        /**
         * key:register+phone
         */
        //3.从redis中取
        Object redisCode = redisTemplate.opsForValue().get(UserConstants.REGISTERCODE + phone);

        String code = "";
        //判断redisCode是否存在
        if(redisCode!=null){  //三分钟内发送过
            //判断是否超过一分钟
            if(System.currentTimeMillis()-Long.valueOf(redisCode.toString().split(":")[1])<=1*60*1000){
                //没超过一分钟
                throw new BusinessException("一分钟之内请勿频繁发送");
            }else {
                //超过一分钟
                code = redisCode.toString().split(":")[1];
            }



        }else {  //第一次发送
            //生成验证码
            code = StrUtils.getComplexRandomString(4);

        }
        //把验证码存入redis中，并且发送短信
        redisTemplate.opsForValue().set(
                UserConstants.REGISTERCODE + phone,
                code+":"+System.currentTimeMillis(),
                3,//时间
                TimeUnit.MINUTES //时间单位
        );
        //发送短信
        SmsUtil.sendSms(phone, "验证码为:"+code+"请在三分钟内使用");

    }
}
